<?php

namespace App\Listeners;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Models\Account\UserLog;

class UserEventSubscriber
{

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        //
    }

    /**
     * Handle user login events.
     */
    public function onUserLogin($event)
    {
        $data = $this->_ip();
        $data['user_id'] = $event->user->id;
        $data['type'] = 0;
        $data['data_scope'] = $event->user->data_scope;
        $log = new UserLog();
        $log->addLog($data);
    }

    /**
     * Handle user logout events.
     */
    public function onUserLogout($event)
    {
        $data = $this->_ip();
        $data['user_id'] = $event->user->id;
        $data['type'] = 1;
        $data['data_scope'] = $event->user->data_scope;
        $log = new UserLog();
        $log->addLog($data);
    }

    /**
     * Register the listeners for the subscriber.
     *
     * @param  \Illuminate\Events\Dispatcher  $events
     */
    public function subscribe($events)
    {
        $events->listen(
                'Illuminate\Auth\Events\Login', 'App\Listeners\UserEventSubscriber@onUserLogin'
        );

        $events->listen(
                'Illuminate\Auth\Events\Logout', 'App\Listeners\UserEventSubscriber@onUserLogout'
        );
    }

    public function _ip()
    {
        //获取客户端真实ip地址
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $clientIp = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $clientIp = $_SERVER["HTTP_CLIENT_IP"];
        } else if (isset($_SERVER["REMOTE_ADDR"])) {
            $clientIp = $_SERVER["REMOTE_ADDR"];
        } else if (getenv("HTTP_X_FORWARDED_FOR")) {
            $clientIp = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $clientIp = getenv("HTTP_CLIENT_IP");
        } else if (getenv("REMOTE_ADDR")) {
            $clientIp = getenv("REMOTE_ADDR");
        } else {
            $clientIp = "Unknown";
        }

        $data = [];
        $data['ip'] = $clientIp;
        return $data;
//        try {
//            $response = file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip=' . $clientIp);
//            $result = json_decode($response, true);
//            if ($result) {
//                $data['address'] = $result['data']['city'] . '(' . $result['data']['city_id'] . ')' . '.' . $result['data']['isp'];
//            }
//            return $data;
//        } catch (\Exception $e) {
//            return $data;
//        }
    }

}
